package com.mq.core;

import com.mq.core.container.AbstractMessageListenerContainer;
import com.mq.core.endpoint.RedisListenerEndpoint;
import com.mq.core.factory.RedisListenerContainerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RedisListenerEndpointRegistrar {

    final private Map<String, AbstractMessageListenerContainer> listenerContainers =
            new ConcurrentHashMap<String, AbstractMessageListenerContainer>();

    public void registerEndpoint(RedisListenerEndpoint endpoint, RedisListenerContainerFactory factory){

        synchronized (this.listenerContainers){
            if(listenerContainers.containsKey(endpoint.getId())){
                return;
            }
            AbstractMessageListenerContainer listenerContainer = factory.createListenerContainer(endpoint);
            listenerContainers.put(endpoint.getId(), listenerContainer);
            //listenerContainer.start();
        }
    }

    public void startContainer(){
        for(AbstractMessageListenerContainer container : listenerContainers.values()){
            container.start();
        }
    }

    public void stopAll(){
        startOrStop(true);
    }

    public void startAll(){
        startOrStop(false);
    }

    private void startOrStop(boolean quit){
        for(AbstractMessageListenerContainer container : listenerContainers.values()){
            container.setQuit(quit);
        }
    }

    public void startOne(String id){
        AbstractMessageListenerContainer container = get(id);
        if(container != null){
            container.setQuit(false);
        }
    }

    public void stopOne(String id){
        AbstractMessageListenerContainer container = get(id);
        if(container != null){
            container.setQuit(true);
        }
    }

    public AbstractMessageListenerContainer get(String id){
        return listenerContainers.get(id);
    }

    public Map<String, AbstractMessageListenerContainer> getListenerContainers() {
        return listenerContainers;
    }
}
